package com.li.controller;

import com.li.common.config.Result;
import com.li.mapper.AdviceMapper;
import com.li.pojo.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/advice")
public class AdviceController {
  @Autowired
  AdviceMapper adviceMapper;
  
  
  /**
   * 获取公告列表
   * @param page 当前页面
   * @param rows 页面显示的条数
   * @return
   */
  @GetMapping("")
  public Result<?> getStudents(@RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer rows) {
    Map<String, Object> ret = new HashMap<String, Object>();
    Map<String, Object> queryMap = new HashMap<String, Object>();
    queryMap.put("offset", ((page - 1) * rows));
    queryMap.put("pageSize", rows);
    ret.put("rows", adviceMapper.findAdvList(queryMap));
    ret.put("total", adviceMapper.getAdvTotal(queryMap));
    return Result.success(ret);
  }
  
  /**
   * 新增公告
   * @param advice 公告类
   * @return
   */
  @PostMapping
  public Result<?> save(@RequestBody Advice advice) {
    //自动更新创作时间
    advice.setCtime(new Date());
    adviceMapper.addAdvice(advice);
    return Result.success();
  }
  
  /**
   * 更新
   * @param advice 公告类
   * @return
   */
  @PutMapping
  public Result<?> update(@RequestBody Advice advice) {
    adviceMapper.updateById(advice);
    return Result.success();
  }
  
  /**
   * 根据id删除
   * @param id
   * @return
   */
  @DeleteMapping("/{id}")
  public Result<?> deleteUser(@PathVariable Integer id) {
    Integer i = adviceMapper.deleteById(id);
    if (i == 0){
      return Result.error("-1", "删除失败");
    }
    return Result.success();
  }
  
}
